//
//  ContactManager.m
//  OC6_作业练习
//
//  Created by dllo on 15/11/1.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "ContactManager.h"
#import "Contact.h"

@implementation ContactManager

- (id)init
{
    self = [super init];
    if (self) {
        [self setData:[[NSMutableDictionary alloc] init]];
    }
    return self;
}




// 3,添加联系人

- (void)addPerson:(Contact *)contact
{
    if (0 == [contact name].length || 0 == [contact phone].length) {
        NSLog(@"添加失败");
    }
    NSString *key = [[contact name] substringToIndex:1];
    NSMutableArray *arr = nil;
    if (nil == [[self data] objectForKey:key]) {
        arr = [NSMutableArray array];
        [[self data] setObject:arr forKey:key];
    }else{
        arr = [[self data] objectForKey:key];
    }
    [arr addObject:contact];
}


// 4,获取某个分组名称下所有联系人，并且按照姓名升序排列。

- (NSMutableArray *)sortByName:(NSString *)key
{
    if (0 == key.length) {
        return nil;
    }
    NSMutableArray *arr = nil;
    arr = [[self data] objectForKey:key];
    [arr sortUsingSelector:@selector(compareByName:)];
    return arr;
}


// 5,从通讯录中根据电话号码搜索联系人。

- (NSMutableArray *)searchByPhone:(NSString *)phone
{
    if (0 == phone.length) {
        return nil;
    }
    NSMutableArray *arr = [NSMutableArray array];
    for (NSString *key in [self data]) {
        for (Contact *contact in [[self data] objectForKey:key]) {
            if ([[contact phone] isEqualToString:phone]) {
                [arr addObject:contact];
            }
        }
    }
    return arr;
}


// 6,获取所有女性的联系人，并且按照年龄的降序排列。

- (NSMutableArray *)sortByAge
{
    NSMutableArray *arr = [NSMutableArray array];
    for (NSString *key in [self data]) {
        for (Contact *contact in [[self data] objectForKey:key]) {
            if ([[contact sex] isEqualToString:@"female"]) {
                [arr addObject:contact];
            }
        }
    }
    [arr sortUsingSelector:@selector(compareByAge:)];
    return arr;
}

// 7,根据姓名删除某个联系人。

- (void)deleteByName:(NSString *)name
{
    NSString *key = [name substringToIndex:1];
    NSMutableArray *arr = [[self data] objectForKey:key];
    for (NSInteger i = 0; i < arr.count; i++) {
        if ([[[arr objectAtIndex:i] name] isEqualToString:name]) {
            [arr removeObjectAtIndex:i];
        }
    }
}


// 8, 删除某个分组的全部联系人。

- (void)deleteByKey:(NSString *)key
{
    [[self data] removeObjectForKey:key];
}









// 1,显示联系人信息

- (void)infoAllContact
{
    for (NSString *key in [self data]) {
        for (Contact *contact in [[self data] objectForKey:key]) {
            NSLog(@"%@ %@ %@ %@ %@ %ld", [contact name], [contact sex], [contact phone], [contact address], [contact group], [contact age]);
        }
    }
}









@end
